﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using Portal.Environment;
using Portal.Language;
using Portal.Interface;
using System.Text.RegularExpressions;

namespace Portal.CDSP
{
    public class FNewsByCategoryWP : WebPart
    {
        public override string WebPartId
        {
            get
            {
                return "WebSite.FNewsByCategoryWP";
            }
        }

        public override string WebPartFolder
        {
            get
            {
                return "Portal.CDSP";
            }
        }

        public override string Title
        {
            get
            {
                return GetText("FTitle", "CDSP-Danh mục tin theo nhóm");
            }
        }

        public override ViewCls[] Views
        {
            get
            {
                return new ViewCls[]{
                    new ViewCls("default",GetText("default","Danh mục tin theo nhóm"),1),
                };
            }
        }

        public override string NameSpace
        {
            get
            {
                return "Portal.CDSP";
            }
        }

        public override string ClassName
        {
            get
            {
                return "FNewsByCategoryWP";
            }
        }


        [AjaxPro.AjaxMethod()]
        public string GetHtml(
            string TabModuleId,
            string belongSite,
            string ShortGroupNewsItemId,
            int ItemsPerRow,
            int NoOfVisiblePage,
            int CurrentPage,
            string JumpJavaScript)
        {
            string pc = "vvvxxx!@#$abc*()";
            StringBuilder Html = new StringBuilder();
            const int MaxValue = 40;
            FSpecialSubjectCls GroupNewsItemCls = new FSpecialSubjectBLL().CreateModelItem(ShortGroupNewsItemId, belongSite);
            DataTable dtNews = NewsByCategoryBLL.ReadingNews(GroupNewsItemCls.GroupNewsItemId);
            TabModuleCls TabModuleCls = new TabModuleBLL().CreateModelFromXml(TabModuleId);
            if (TabModuleCls == null) throw new Exception("[" + TabModuleId + "] " + GetText("TabModuleIdNull", "not found!"));
            int StartIndex = 0;
            int EndIndex = 0;

            string menuUrl = Environments.GetNewsCategoryUrl(belongSite, ShortGroupNewsItemId, GroupNewsItemCls.GroupNewsItemName, "_runtime");
            string PagingText = new CDSPPaging().GetPaging(TabModuleId, belongSite, dtNews.Rows.Count, ItemsPerRow, NoOfVisiblePage, CurrentPage, JumpJavaScript, ref StartIndex, ref EndIndex);
            Html.Append(
                Environments.GetExtraStyleSheet(TabModuleCls) +
                "<input type=hidden id=txtBelongSite value=\"" + belongSite + "\">" +
                "<div id = divProcessing></div>" +
                "<input id=txtShortGroupNewsItemId type=hidden value=\"" + ShortGroupNewsItemId + "\">" +                
                "<div class=\"PageTitleBar\">\n" +
                "				<ul class=\"breadcrumb\">\n" +
                "					<li class=\"breadcrumblv2\">"+"<h3><a href=\"" + menuUrl + "\">" + GroupNewsItemCls.GroupNewsItemName.ToUpper() + "</a></h3></li>\n" +
                "				</ul>\n" +
                "				<div class=\"clr\"></div>\n" +
                "</div>"+
                "<div class=\"ArticleDetail\">\n");
            for (int iNews = StartIndex; iNews < EndIndex; iNews++)
            {
                string ShortId = string.Empty;
                try
                {
                    ShortId = (string)dtNews.Rows[iNews]["ShortId"];
                }
                catch { }
                DateTime EntryDate = (DateTime)dtNews.Rows[iNews]["EntryDate"];
                string Subject = string.Empty;
                try
                {
                    Subject = (string)dtNews.Rows[iNews][Environments.ActiveLanguage + "Subject"];
                }
                catch { }
                if (Subject.Trim().Length == 0)
                {
                    Subject = GetText("NoTitle", "(Không có tiêu đề)");
                }
                string ShortContent = string.Empty;
                try
                {
                    ShortContent = (string)dtNews.Rows[iNews][Environments.ActiveLanguage + "ShortContent"];
                }
                catch { }
                if (Environments.UseEncypt == 1)
                {
                    try
                    {
                        ShortContent = new RSACSPCls().Decrypt(pc, (string)dtNews.Rows[iNews][Environments.ActiveLanguage + "EcryptShortContent"]);
                    }
                    catch { ShortContent = ""; }
                }
                string Url = Environments.GetNewsUrl(belongSite, ShortId, Subject, "_runtime");
                string SmallImage = string.Empty;
                try
                {
                    SmallImage = (string)dtNews.Rows[iNews]["SmallImage"];
                }
                catch { }
                bool HasImage = SmallImage.Trim().Length > 0;                
                int Count = 0;
                int j = 0;
                ShortContent = Regex.Replace(ShortContent, @"<(.|\n)*?>", string.Empty);
                int Length = ShortContent.Length;
                for (int i = 1; i < ShortContent.Length; i++)
                {
                    if (ShortContent[i - 1].ToString().Equals(" ") && !ShortContent[i].ToString().Equals(" "))
                        Count++;
                    if (Count <= MaxValue)
                    {
                        j = i;
                    }
                }
                if (Count > MaxValue)
                {

                    ShortContent = ShortContent.ToString().Remove(j, (Length - j));
                    ShortContent = string.Concat(ShortContent, "...");
                }

                Html.Append(
                        "<div class=\"leftsubContentwrappin\">" +
                        "<h3><a href=" + Url + ">" + Subject + "</a>" +
                        "<span class=greynews>(" + EntryDate.ToString("dd/MM/yyyy") + ")</span>" +
                        "</h3>" +
                        "<div class=\"clrfix\"></div>");
                if (HasImage)
                {
                    string ImageUrl = Environments.HttpMediaRoot + "/media/" + Environments.PortalAlias + "/news/images/" + belongSite + "/" + SmallImage;
                    Html.Append("<a href=\"" + Url + "\"><img src=\"" + ImageUrl + "\" /></a>");
                }
                else {                    
                    string ImageUrl = "images/no_photo.jpg";
                    Html.Append("<a href=\"" + Url + "\"><img src=\"" + ImageUrl + "\" /></a>");
                }
                Html.Append(
                        "<p>" + ShortContent + "</p>" +
                        "<div class=colfix></div>" +
                        "</div>");
            }                           
            if (PagingText.Trim().Length > 0)
            {
                Html.Append(PagingText);
            }
            Html.Append("</div>");
            //Html.Append("</div>");
            return Html.ToString();
        }
        

        private string ClientRenderWebPart(string TabModuleId, string HasPorlet, ref string ModuleTitle)
        {
            try
            {
                TabModuleCls TabModuleCls = new TabModuleBLL().CreateModelFromXml(TabModuleId);
                if (TabModuleCls == null) throw new Exception("[" + TabModuleId + "] " + GetText("TabModuleIdNull", "not found!"));
                string ShortGroupNewsItemId = (string)Environments.Request("gid");
                string belongSite = TabModuleCls.belongSite;
                if (ShortGroupNewsItemId == null)
                {
                    return GetText("IdIsNull", "Không tìm thấy") + " " + ShortGroupNewsItemId;
                }

                FSpecialSubjectCls GroupNewsItemCls = new FSpecialSubjectBLL().CreateModelItem(ShortGroupNewsItemId, TabModuleCls.belongSite);
                DataTable dtNews = NewsByCategoryBLL.ReadingNews(GroupNewsItemCls.GroupNewsItemId);
                string MenuName = "";
                string menuUrl = "";
                DataTable dtGroup = new FSpecialSubjectBLL().ReadingGroupNewsItemName(GroupNewsItemCls.GroupNewsItemId);
                if (dtGroup.Rows.Count == 0)
                {
                    DataTable jdtGroup = new FSpecialSubjectBLL().ReadingMenu(GroupNewsItemCls.GroupNewsId);
                    MenuName = (string)jdtGroup.Rows[0]["" + Environments.ActiveLanguage + "Subject"];
                    menuUrl = Environments.GetNewsCategoryUrl(TabModuleCls.belongSite, GroupNewsItemCls.GroupNewsItemId, GroupNewsItemCls.GroupNewsItemName, "_runtime");
                }
                else
                {
                    MenuName = (string)dtGroup.Rows[0]["" + Environments.ActiveLanguage + "GroupNewsItemName"];
                    menuUrl = (string)dtGroup.Rows[0]["JumpUrl"];
                }
                ModuleTitle = MenuName;
                string Html =
                    Environments.GetExtraStyleSheet(TabModuleCls) +
                        "<script language=javascript>" +
                        " function ClientJumpPageNews(TabModuleId,MaxItems, ItemsPerRow, NoOfVisiblePage, CurrentPage, JumpJavaScript)" +
                        "  {" +
                        "      document.getElementById(\"divProcessing\").innerHTML = Portal.CDSP.FNewsByCategoryWP.GetProcessingText().value;" +
                        "      setTimeout(\"RealJumpPageNews('\"+TabModuleId+\"',\"+MaxItems+\",\"+ItemsPerRow+\",\"+NoOfVisiblePage+\",\"+CurrentPage+\",'\"+JumpJavaScript+\"')\",10);" +
                        "  }" +
                        "  function RealJumpPageNews(TabModuleId,MaxItems, ItemsPerRow, NoOfVisiblePage, CurrentPage, JumpJavaScript)" +
                        "  {" +
                        "      ShortGroupNewsItemId=document.getElementById(\"txtShortGroupNewsItemId\").value;" +
                        "      PageIndex = CurrentPage;" +
                        "      belongSite=document.getElementById(\"txtBelongSite\").value;" +
                        "      retValue=Portal.CDSP.FNewsByCategoryWP.GetHtml(TabModuleId,belongSite,ShortGroupNewsItemId,ItemsPerRow,NoOfVisiblePage,CurrentPage,JumpJavaScript).value;" +
                        "      if(retValue.indexOf(\"ERROR\")!=-1)" +
                        "      {" +
                        "          alert(retValue);" +
                        "          return;" +
                        "      }" +
                        "      document.getElementById(\"divProcessing\").innerHTML=\"\";" +
                        "      document.getElementById(\"divNewsByCategory\").innerHTML=retValue;" +
                        "  }" +
                        "</script>" +
                        "<div id=\"leftsub\">"+
                            GetHtml(TabModuleId, belongSite, ShortGroupNewsItemId, 10, 10, 0, "ClientJumpPageNews") +
                        " </div>";

                return Html;
            }
            catch (Exception ex)
            {
                return "ERROR:" + ex.Message;
            }
        }

        public override RenderInfoCls ClientRenderWebPartWithInfo(string BelongSite, string TabModuleId, string ViewName, string HasPorlet, LoadParamCls loadParamCls)
        {
            RenderInfoCls oRenderInfoCls = new RenderInfoCls();
            oRenderInfoCls.Error = true;
            oRenderInfoCls.ErrorMsg = GetText("ViewNotFound", "Không tìm thấy View [" + ViewName + "]");
            try
            {
                if (ViewName.Equals("default"))
                {
                    oRenderInfoCls.Content = ClientRenderWebPart(TabModuleId, HasPorlet, ref oRenderInfoCls.ModuleTitle);
                    oRenderInfoCls.Error = false;
                    oRenderInfoCls.ErrorMsg = "";
                }
                return oRenderInfoCls;
                //return ResourceBLL.GetText(WebPartId, "ViewNotFound", "Không tìm thấy View [" + ViewName + "]");
            }
            catch (Exception ex)
            {
                oRenderInfoCls.ErrorMsg = ex.Message.ToString();
                oRenderInfoCls.Error = true;
                return oRenderInfoCls;
            }
        }


        public override DataTable ReadingDataService(string belongSite, string ActiveLanguage, ref string IdField, ref string SubjectField)
        {
            IdField = "Id";
            SubjectField = "Subject";
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("Id");
            dtResult.Columns.Add("Subject");
            dtResult.Rows.Add(new object[]{
                "115FE4D2-FDE4-4ffe-B37C-F2C0E7C0DBDD","Danh sách tin theo nhóm"
            });
            return dtResult;
        }


        [AjaxPro.AjaxMethod]
        public string GetProcessingText()
        {
            string Url = Environments.GetActiveThemeUrl() + "/Global/Loading.gif";
            return "<img src=\"" + Url + "\"><a class=cssProcessing>" + GetText("ProcessingText", "Đang đọc dữ liệu...") + "</a>";
        }

        public override bool AllowFrontService
        {
            get
            {
                return true;
            }
        }

        public override void RegAjaxPro(System.Web.UI.Page ActivePage)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(Portal.CDSP.FNewsByCategoryWP), ActivePage);
        }
    }
}
